//
//  ProjectCell.swift
//  mggz
//
//  Created by ShareAnimation on 2017/8/8.
//  Copyright © 2017年 爱丽丝的梦境. All rights reserved.
//

import UIKit
import SnapKit

class ProjectCell: UITableViewCell {
    
    enum ProjectStatus {
        case onJob
        case inApply
        case isLeaved   //离职
        case prepareApply
        case checked //已验收
    }
    
    var isCellSelected = false {
        willSet {
            self.isCellSelected = newValue
            self.configAccessoryView()
        }
    }
    
    var projectStatus: ProjectStatus? {
        willSet {
            self.projectStatus = newValue
            self.configAccessoryView()
        }
    }
    
    var panel = UIView()
    
    var projectNameLabel: UILabel = {
        let label = UILabel()
        label.textColor = colorWith255RGB(51, g: 51, b: 51)
        if(SCREEN_WIDTH>320){
            label.font = wwFont_Medium(20)
        }else{
            label.font = wwFont_Medium(17)
        }
        label.numberOfLines = 0
        label.text = "宁波工程学院专业承包劳务服务包"
        return label
    }()
    
    //发包编号 title
    var contractNumberLabel: UILabel = {
        let label = UILabel()
        label.text = "发包编号:"
        label.font = wwFont_Regular(15)
        label.textColor = UIColor.mg_lightGray
        return label
    }()
    
    var contractNumberDetailLabel: UILabel = {
        let label = UILabel()
        label.font = wwFont_Regular(15)
        label.textColor = colorWith255RGB(240, g: 65, b: 52)
        return label
    }()
    
    var companyIconImageView: UIImageView = {
        let imageView = UIImageView()
        imageView.image = UIImage(named: "Icon_公司")!.withRenderingMode(.alwaysTemplate)
        imageView.tintColor = UIColor.mg_blue
        return imageView
    }()
    
    var companyLabel: UILabel = {
        let label = UILabel()
        label.text = "宁波劳务企业有限公司"
        label.font = wwFont_Regular(15)
        label.textColor = UIColor.mg_lightGray
        return label
    }()
    
//    var salaryLabel:UILabel = {
//        let label = UILabel()
//        label.text = "工资:"
//        label.font = wwFont_Regular(15)
//        label.textColor = UIColor.mg_lightGray
//        return label
//    }()
    
    var addressIconImageView: UIImageView = {
        let imageView = UIImageView()
        imageView.image = UIImage(named: "Icon_地址")!.withRenderingMode(.alwaysTemplate)
        imageView.tintColor = colorWith255RGB(240, g: 65, b: 52)
        return imageView
    }()
    
    var addressLabel:UILabel = {
        let label = UILabel()
        label.text = "宁波镇海区中官西路777号汇智大厦601室"
        label.font = wwFont_Regular(15)
        label.numberOfLines = 0
        label.textColor = UIColor.mg_lightGray
        return label
    }()
    
//    /// 工资
//    var everydayPaymentLabel: UILabel = {
//        let label = UILabel()
//        label.font = wwFont_Regular(13)
//        label.text = "工资："
//        return label
//    }()
    
    /// 工资内容
//    var salaryDetailLabel: UILabel = {
//        let label = UILabel()
//        label.font = wwFont_Medium(15)
//        label.textColor = UIColor.red
//        return label
//    }()
    
//    /// 每日工作时长
//    var everydayWorkingTimeLabel: UILabel = {
//        let label = UILabel()
//        label.font = wwFont_Regular(13)
//        label.text = "每日工作时长:"
//        label.textColor = UIColor.mg_lightGray
//        return label
//    }()
//
//    /// 每日工作时长内容
//    var everydayWorkingTimeDetailLabel: UILabel = {
//        let label = UILabel()
//        label.font = wwFont_Regular(15)
//        label.textColor = UIColor.mg_lightGray
//        return label
//    }()
    
    lazy var customAccessoryView: UIView = UIView()
    var projectModel:ProjectModel?
    
    var callInHandler: (()->Void)?//点击调入项目处理器

    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        self.backgroundColor = UIColor.white
        self.selectionStyle = .none
        self.setupViews()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    var bottomConstraint:Constraint?
    
    func setupViews() {
        
        self.selectedBackgroundView = UIView()
        self.selectedBackgroundView?.backgroundColor =  colorWith255RGB(242, g: 243, b: 245)

        self.contentView.addSubview(self.panel)
        self.panel.snp.makeConstraints { (make) in
            make.left.bottom.top.equalTo(self.contentView)
        }
        
        self.panel.addSubview(self.projectNameLabel)
        self.projectNameLabel.snp.makeConstraints { (make) in
            make.top.equalTo(self.panel).offset(8)
            make.left.equalTo(self.panel).offset(18)
            make.right.equalTo(self.panel)
           // make.height.equalTo(24)
        }
        
        self.panel.addSubview(self.contractNumberLabel)
        self.contractNumberLabel.snp.makeConstraints { (make) in
            make.left.equalTo(self.projectNameLabel)
        make.top.equalTo(self.projectNameLabel.snp.bottom).offset(5)
            make.height.equalTo(20)
            make.width.equalTo(68)
        }
        
        self.panel.addSubview(self.contractNumberDetailLabel)
        self.contractNumberDetailLabel.snp.makeConstraints { (make) in
            make.left.equalTo(self.contractNumberLabel.snp.right).offset(0)
            make.top.bottom.equalTo(self.contractNumberLabel)
                make.width.equalTo(116)
            //make.right.equalTo(self.projectNameLabel)
        }
        
        self.panel.addSubview(companyIconImageView)
        self.companyIconImageView.snp.makeConstraints { (make) in
            make.left.equalTo(self.contractNumberLabel)
        make.top.equalTo(self.contractNumberLabel.snp.bottom).offset(0)
            make.width.height.equalTo(20)
        }
    
        self.panel.addSubview(companyLabel)
        self.companyLabel.snp.makeConstraints { (make) in
        make.left.equalTo(self.companyIconImageView.snp.right).offset(5)
            make.bottom.equalTo(self.companyIconImageView)
        }
        self.panel.addSubview(addressIconImageView)
        self.addressIconImageView.snp.makeConstraints { (make) in
            make.left.size.equalTo(self.companyIconImageView)
            make.top.equalTo(self.companyIconImageView.snp.bottom).offset(5)
        }
        self.panel.addSubview(addressLabel)
        self.addressLabel.snp.makeConstraints { (make) in
            make.top.equalTo(self.addressIconImageView)
        make.left.equalTo(self.addressIconImageView.snp.right).offset(5)
            make.right.equalTo(self.contentView).offset(-30)
           // make.bottom.equalTo(self.contentView).offset(-5)
        }
        
        self.panel.snp.makeConstraints({ (make) in
            self.bottomConstraint = make.bottom.equalTo(self.addressLabel.snp.bottom).constraint
        })
        
    }
    
    fileprivate func configAccessoryView() {
    self.contentView.addSubview(self.customAccessoryView)
        self.customAccessoryView.snp.makeConstraints { (make) in
            make.top.bottom.right.equalTo(self.contentView)
            make.width.equalTo(80)
            make.left.equalTo(self.panel.snp.right)
        }
        
        if let status = self.projectStatus {
            for view in self.customAccessoryView.subviews {
                view.removeFromSuperview()
            }
            
            self.bottomConstraint?.deactivate()//移除
            self.panel.snp.makeConstraints({ (make) in
                self.bottomConstraint = make.bottom.equalTo(self.addressLabel.snp.bottom).constraint
            })
           
            switch status {
                case .onJob,.inApply, .isLeaved, .checked:
                let label = UILabel()
                label.textAlignment = .right
                label.font = wwFont_Regular(15)
                self.customAccessoryView.addSubview(label)
                label.snp.makeConstraints({ (make) in
                    make.top.equalTo(self.customAccessoryView).offset(5)
                    make.right.equalTo(self.customAccessoryView).offset(-8)
                })
                
                let roundDotView = UIView()
                roundDotView.layer.cornerRadius = 5
                self.customAccessoryView.addSubview(roundDotView)
                roundDotView.snp.makeConstraints({ (make) in
                    make.centerY.equalTo(label)
//                    make.left.equalTo(self.customAccessoryView).offset(3)
                    make.right.equalTo(label.snp.left).offset(-3)
                    make.width.height.equalTo(10)
                })
                
                if self.isCellSelected {
                    let selectedSign = UIImageView()
                    selectedSign.image = UIImage(named: "reth_dagou")
                    selectedSign.contentMode = .scaleAspectFit
                    self.customAccessoryView.addSubview(selectedSign)
                    selectedSign.snp.makeConstraints({ (make) in
                    make.right.equalTo(self.customAccessoryView).offset(-4)
                    make.bottom.equalTo(self.customAccessoryView).offset(-6)
                        make.width.height.equalTo(20)
                        
                    })
                }
                
                if status == .onJob {
                    label.text = "在职"
                    label.textColor = colorWith255RGB(62, g: 207, b: 110)
                    roundDotView.backgroundColor = colorWith255RGB(62, g: 207, b: 110)
                }
                else if status == .isLeaved {
                    label.text = "离职"
                    label.textColor = colorWith255RGB(153, g: 153, b: 153)
                    roundDotView.backgroundColor = colorWith255RGB(153, g: 153, b: 153)
                }
                else if status == .checked {
                    label.text = "已完结"
                    label.textColor = colorWith255RGB(153, g: 153, b: 153)
                    roundDotView.backgroundColor = colorWith255RGB(153, g: 153, b: 153)
                }
                else {
                    label.text = "申请中"
                    label.textColor = colorWith255RGB(255, g: 191, b: 0)
                    roundDotView.backgroundColor = colorWith255RGB(255, g: 191, b: 0)
                }
            case .prepareApply:
                let button = UIButton()
                button.setTitle("调入申请", for: .normal)
                button.addTarget(self, action: #selector(doApplyActon), for: .touchUpInside)
                button.setTitleColor(UIColor.mg_blue, for: .normal)
                button.layer.borderColor = UIColor.mg_blue.cgColor
                button.layer.borderWidth = 1
                button.layer.cornerRadius = 5
                button.titleLabel?.font = wwFont_Regular(12)
                self.customAccessoryView.addSubview(button)
                button.snp.makeConstraints({ (make) in
                    make.left.equalTo(self.customAccessoryView).offset(5)
                    make.right.equalTo(self.customAccessoryView).offset(-5)
                    make.centerY.equalTo(self.customAccessoryView)
//                    make.width.equalTo(60)
                })
                
            }

        }
    }
    func bind(_ model: ProjectModel) {
        self.projectModel = model
            
        self.projectNameLabel.text = model.projectName
        self.companyLabel.text = model.companyName
        self.addressLabel.text = model.address
        self.contractNumberDetailLabel.text = model.orderNo
        
//        let daySalaryFloat:Float!
//        if model.daySalary != nil {
//            daySalaryFloat = Float(model.daySalary!)
//        }
//        else {
//         daySalaryFloat = 0
//        }
//        self.salaryDetailLabel.text = "\(Int(daySalaryFloat))元/天"
        
        
        
//        if model.workDayType != 2{
//
//            self.salaryDetailLabel.text = newdaySalaryStr! + "元/工"
//
//        }else{
//
//           self.salaryDetailLabel.text = daySalaryStr! + "元/小时"
//        }
        
       // self.everydayWorkingTimeDetailLabel.text = (model.workHours ?? "--") + "小时"
        
        guard self.accessoryType != .disclosureIndicator else {
            self.panel.snp.makeConstraints { (make) in
                make.left.bottom.top.equalTo(self.contentView)
                make.right.equalTo(self.contentView).offset(-20)
            }
            return
        }
        
        guard !model.isLeaved else{
            self.projectStatus = .isLeaved
            return
        }
        //如果projectStatus大于3，则默认为已验收，不用在判断其他情况
        guard model.projectStatus != nil ,model.projectStatus!.rawValue < 3 else{
            self.projectStatus = .checked
            return
        }
        
        if model.isAppSelected {
//            print(model.projectName)
        }
        self.isCellSelected = model.isAppSelected
        
        if model.isWorking {
            self.projectStatus = .onJob
            
        }
        else if model.isApply {
            self.projectStatus = .inApply
        }
        else {
            self.projectStatus = .prepareApply
            if model.demandBaseMigrantWorkerID == nil {
               
            }
            else {
                
            }
        }

    }
    
    func doApplyActon() {
        
        let alertController = ETSimpleAlertController.init("您确定要申请调入这个项目吗？") {
            guard let model = self.projectModel else {
                return
            }
            
            let orderConfigId = "902a7ce5-1920-788e-1f59-59d44ce2a85c"
            var guid: String?
            var orderNo: String?
            
            let dispatchGroup = DispatchGroup()
            
            WWBeginLoadingWithStatus("开始调入")
            dispatchGroup.enter()
            UserModel.getGuid { (response) in
                if response.success{
                    guid = response.value
                }
                else {
                    
                }
                dispatchGroup.leave()
            }
            
            dispatchGroup.enter()
            UserModel.getOrderNo(orderConfigId: orderConfigId) { (response) in
                if response.success {
                    orderNo = response.value
                }
                else {
                   
                }
                dispatchGroup.leave()
            }
            
            
            dispatchGroup.notify(queue: DispatchQueue.main) {
                guard guid != nil else {
                    WWError("获取guid出错")
                    return
                }
                guard orderNo != nil else {
                    WWError("获取orderNo出错")
                    return
                }
                
                ProjectModel.callInProject(guid!, marketSupplyBaseID: model.marketSupplyBaseID!, businessChangerID: model.businessChangerID!, migrantWorkerID: model.migrantWorkerId!, orderNo: orderNo!, orderConfigId: orderConfigId){(response) in
                    if response.success {
                        WWSuccess("提交成功，等待审批！")
                        if let handler = self.callInHandler {
                            handler()
                        }
                    }
                    else{
                        WWError(response.message)
                    }
                }
            }
        }
        Tool.topViewController().present(alertController, animated: true, completion: nil)
    }

}
